/**
 * Created by Mark_ren on 2017/5/22.
 * 苟富贵,無相忘
 */
var moment = require("moment");
var co = require('co');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');
var formidable = require('formidable');
var fs = require('fs');
var literatureController = {

    /**
     *  危重症时间 查找文献
     * @param req
     * @param res
     */
    getJWlisteratureList: function (req, res) {
        co(function () {
            var page = parseInt(req.query.page);
            var params = {};
            var paramT = {};
            paramT.include = [{ model: seq.dictionaryModule, attributes: ['codeDesc'] }]
            //根据id
            if (req.query.id != undefined) {
                params["id"] = req.query.id;
            }

            if (req.query.item != undefined) {
                params["item"] = parseInt(req.query.item);
            }
            if (req.query.sort != undefined) {
                params["sort"] = parseInt(req.query.sort);
            }
            if (req.query.type != undefined && req.query.type != 0) {
                params["type"] = parseInt(req.query.type);
            }
            //模糊查询
            if (req.query.title != undefined) {
                params["title"] = { "$like": "%" + req.query.title + "%" };
            }
            paramT["where"] = params;
            paramT["order"] = [["createTime", 'DESC']];
            if (req.query.page != undefined && req.query.rows != undefined) {
                paramT["offset"] = parseInt(req.query.page);
                paramT["limit"] = parseInt(req.query.rows);
            }
            seq.literatureModule.findAndCountAll(paramT).then(function (result) {
                res.json({ "success": true, "page": page, "total": result.count, "result": result.rows });
            });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })


    },
    /**
     *  增加文献
     * @param req
     * @param res
     */
    addListerature: function (req, res) {
        co(function () {

            var uuid = util.getUUID();
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/articleCover";
                form.type = true;
                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields) {

                    fields.id = uuid;
                    fields.createTime = util.getNowTime();
                    seq.literatureModule.create(fields).then(function (results) {
                        console.log(fields.item);
                        if (fields.sort == 303) {
                            res.redirect(util.getIP() + "wzzTime/wzzDocList.html?item=" + fields.item + "&sort=" + fields.sort);
                        } else if (fields.sort == 403) {
                            res.redirect(util.getIP() + "nxgTime/nxgDocList.html?item=" + fields.item + "&sort=" + fields.sort);
                        }

                    });
                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '添加失败' });
            console.log(e);
        })

    },

    /**
     *  更新文献
     * @param req
     * @param res
     */
    updListerature: function (req, res) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/articleCover";
                form.type = true;

                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields) {
                    var params = {};
                    var paramT = {};

                    var paramU = { 'id': req.params.ID };

                    if (fields.title != undefined) {
                        params["title"] = fields.title;
                    }
                    if (fields.copyright != undefined) {
                        params["copyright"] = fields.copyright;
                    }
                    if (fields.products != undefined) {
                        params["products"] = fields.products;
                    }
                    if (fields.type != undefined) {
                        params["type"] = fields.type;
                    }
                    if (fields.score != undefined) {
                        params["score"] = fields.score;
                    }
                    if (fields.abstract != undefined) {
                        params["abstract"] = fields.abstract;
                    }
                    paramT["where"] = paramU;

                    seq.literatureModule.update(params, paramT).then(function (results) {
                        if (fields.sort == 303) {
                            res.redirect(util.getIP() + "wzzTime/wzzDocList.html?item=" + fields.item + "&sort=" + fields.sort);
                        } else if (fields.sort == 403) {
                            res.redirect(util.getIP() + "nxgTime/nxgDocList.html?item=" + fields.item + "&sort=" + fields.sort);
                        }

                    });
                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '修改失败' });
            console.log(e);
        })

    },
    /**
     * 根据 ID 删除图文
     * @param {*} req
     * @param {*} res
     */
    deleteByID: function (req, res) {
        var params = req.query.params;
        var arr = params.split(",");
        try {
            seq.literatureModule.destroy({
                where: {
                    'id': [arr]
                }
            }).then(function (result) {
                res.status(200).json({
                    message: "删除成功！",
                    success: true
                });
            })
        } catch (err) {
            res.status(500).json({
                message: "服务错误！",
                err: err
            });
        }

    }



}
module.exports = literatureController;